<?php

namespace Platform\Repository\Organize;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Platform\Models\Organize\Leader;
use Platform\Models\Organize\Organize;
use Platform\Repository\Repository;

class LeaderRepository extends Repository
{

    public function model()
    {
        return  Leader::class;
    }

    public function getOneByUsername($username)
    {
        return $this->model
            ->where('username', '=', $username)
            ->withTrashed()
            ->first();
    }
    public function getOneByUsernameExpectThis($username,$id)
    {
        return $this->model
            ->where('username', '=', $username)
            ->where('id', '<>', $id)
            ->first();
    }
    public function getOneByPhone($phone)
    {
        return $this->model
            ->where('phone', '=', $phone)
            ->first();
    }

    /**
     * 通过关键词查询
     * @param Request $request
     * @param Organize $organize
     * @return Builder
     */
    public function screen(Request $request,Organize $organize){
        $builder = $this->model->newQuery();
        $builder->where('organize_id', $organize->id);

        $username = $request->get('username',null);
        $name = $request->get('name',null);
        $rolename = $request->get('rolename',null);
        $begin_at = $request->get('begin_at',null);
        $end_at = $request->get('end_at',null);

        $builder->with('role');

        if ($username){
            $builder->where('username', 'like', '%'.$username.'%');
        }
        if ($name){
            $builder->where('name', 'like', '%'.$name.'%');
        }
        if ($begin_at){
            $builder->whereDate('created_at', '>=', $begin_at);
        }
        if ($end_at){
            $builder->whereDate('created_at', '<=', $end_at);
        }
        if ($rolename){
            $builder->whereHas('role', function ($query) use ($rolename){
                $query->where('name', 'like', '%'.$rolename.'%');
            });
        }

        return $builder->paginate(10);
    }


}
